import axios, { type Method } from 'axios'
import { useLoginStore } from '@/stores'
import { storeToRefs } from 'pinia'
import { showToast } from 'vant'
import router from '@/router'
const instance = axios.create({
  // 1. 基础地址，超时时间
  baseURL: 'https://consult-api.itheima.net',
  timeout: 5000
})

instance.interceptors.request.use(
  (config) => {
    //  2. 携带token
    const store = useLoginStore()
    const { loginUser } = storeToRefs(store)
    // 从pinia里面拿token
    if (loginUser.value?.token) {
      config.headers.Authorization = `bearer ${loginUser.value?.token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    // console.log(res)
    // 3. 处理业务失败
    // 正常返回10000，其他表示错误
    if (res.data.code !== 10000) {
      // 1消息提示
      showToast(res.data.message || '服务器错误')
    }
    // 2返回失败的promise
    return Promise.reject(res.data)
  },
  (err) => {
    // 5. 处理401错误
    if (err.request.status === 401) {
      // 1清空登录的用户信息
      const store = useLoginStore()
      store.delLoginUser()
      // 2退出到登录页
      router.push({
        path: '/login',
        query: {
          // 当前路由对象currentRoute
          returnUrl: router.currentRoute.value.fullPath
        }
      })
      // 3消息提示
      showToast('token过期，请重新登录')
    }
    return Promise.reject(err)
  }
)
type Response<T> = {
  code: number
  message: string
  data: T
}
// 封装请求函数
export const request = <T>(
  url: string,
  method: Method = 'GET',
  submitData?: object
) => {
  return instance.request<any, Response<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
  })
}
export default instance
